package com.leyou.sms.mq;


import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsUtil;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.SMS_VERIFY_CODE_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Component
public class MessageListener {

    @Autowired
    private SmsUtil smsUtil;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SMS_VERIFY_CODE_QUEUE,durable = "true"),
            exchange = @Exchange(name = SMS_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = VERIFY_CODE_KEY
    ))
    public void listenCodeMessage(Map<String,String> map) {
        //判断是否为空
        if (CollectionUtils.isEmpty(map)) {
            //为空，垃圾消息，放弃
            return;
        }
        //获取手机号码
        String phone = map.get("phone");
        //判断是否和规范
        if (!RegexUtils.isPhone(phone)) {
            //格式不对
            return;
        }
        //获取code
        String code = map.get("code");
        //判断是否和规范
        if (!RegexUtils.isCodeValid(code)) {
            //格式不对
            return;
        }
        //发短信
        smsUtil.sendVerifyCodeMessage(phone,code);
    }
}
